<template>
  <div class="content">
    <!-- 最上方的表单 -->
    <el-form :inline="true" size="medium">
      <span class="search">
        <el-form-item :label="labelNameC">
          <el-input
            v-model="query.name"
            placeholder="请输入查询内容"
            size="mini"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="企业">
          <el-select v-model="query.unitId" size="mini" @change="elSelectChange">
            <el-option
              v-for="item in unitList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="getSearchFile"
            >查询</el-button
          >
        </el-form-item>
      </span>
      <el-form-item>|</el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="isUploading = true"
          >上传文件</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <div style="height: 87%">
      <el-table
        :data="tableData"
        stripe
        element-loading-background="rgba(245, 245, 245, 0.9)"
        class="el-table-box"
      >
        <el-table-column prop="name" :label="labelNameC"> </el-table-column>
        <el-table-column label="文件大小" width="160">
          <template slot-scope="scope">
            <template v-if="scope.row.size">
              <span v-if="scope.row.size < 1024"
                >{{ Math.round(scope.row.size) }} Byte</span
              >
              <span v-else-if="scope.row.size / 1024 < 1024"
                >{{ (scope.row.size / 1024).toFixed(1) }} KB</span
              >
              <span v-else-if="scope.row.size / 1024 / 1024 < 1024"
                >{{ (scope.row.size / 1024 / 1024).toFixed(1) }} MB</span
              >
              <span v-else
                >{{ (scope.row.size / 1024 / 1024 / 1024).toFixed(1) }} GB</span
              >
            </template>
            <template v-else-if="scope.row.isDir">
              <span v-if="scope.row.length">{{ scope.row.length }}个文件</span>
            </template>
          </template>
        </el-table-column>
        <el-table-column align="center" label="文件类型" width="160">
          <template slot-scope="scope">
            <span v-if="scope.row['ext']">{{ scope.row["ext"] }}</span>
            <span v-else>文件夹</span>
          </template>
        </el-table-column>
        <el-table-column
          label="修改时间"
          prop="lastModifyTime"
          width="230"
          align="center"
        >
        </el-table-column>
        <el-table-column label="操作" width="260" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)"
              >浏览</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="delStation(scope.row)"
              >下载</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="updateFileInfo(scope.row)"
              >修改</el-button
            >
            <el-button type="text" size="small" @click="delFile(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <el-row type="flex" justify="end">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.page"
        :page-sizes="[10, 15]"
        :page-size="query.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-row>
    <!-- 预览模块 -->
    <previewer
      :visible.sync="previewMode"
      ref="previewer"
      @unsupported="previewUnsupported"
      @loading="previewLoading"
    ></previewer>
    <!-- 上传文件提示框 -->
    <el-dialog title="上传文件" :visible.sync="isUploading" width="25%">
      <el-form label-width="120px" label-position="center">
        <el-form-item label="企业">
          <el-select v-model="uploadUnitId" size="mini" @change="elUploadSelectChange">
            <el-option
              v-for="item in unitList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-upload
          class="upload-demo"
          ref="upload"
          :action="action"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :file-list="fileList"
          :auto-upload="false"
          name="file"
          :headers="importHeaders"
        >
          <el-button slot="trigger" size="small" type="primary"
            >选取文件</el-button
          >
          <el-button
            style="margin-left: 10px"
            size="small"
            type="success"
            @click="submitUpload()"
            >上传文件</el-button
          >
        </el-upload>
      </el-form>
    </el-dialog>
    <!-- 修改文件提示框 -->
    <el-dialog title="修改文件" :visible.sync="isChangingFile" width="30%">
      <el-form :model="editForm" ref="editForm" label-width="100px">
        <el-form-item label="文件名">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="简介">
          <el-input type="textarea" v-model="editForm.description"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="commitChangeFile">确 定</el-button>
        <el-button @click="isChangingFile = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Previewer from "../file-list/Previewer";
import { getFileList, getSearchFile, getUnitNameList } from "../../api/user";
import { BACKEND_ROOT } from "../../Constants";
import axios from "axios";
export default {
  name: "AsyncFileList",
  components: { Previewer },
  props: {
    /**
     * 文件夹的uniqueName
     */
    uniqueName:{
      type:String,
      required:true
    },
    defaultUnitId:{
      type:Number,
      required: true
    },
    /**
     * 列表名
     */
    labelName: {
      type: String,
      default: "资源",
    },
    /**
     * 是否显示文件大小
     */
    showSize: {
      type: Boolean,
      default: true,
    },
    /**
     * 是否显示修改日期
     */
    showModifyTime: {
      type: Boolean,
      default: true,
    },
    /**
     * 是否显示操作列表
     */
    showOperator: {
      type: Boolean,
      default: true,
    },
    /**
     * 是否显示上传按钮
     */
    showUpload: {
      type: Boolean,
      default: true,
    },
    /**
     * 是否显示新建文件夹按钮
     */
    showMkdir: {
      type: Boolean,
      default: true,
    },
    /**
     * 是否显示搜索栏
     */
    showSearch: {
      type: Boolean,
      default: true,
    },
    /**
     * 是否显示分隔符
     */
    showSeparator: {
      type: Boolean,
      default: true,
    },
    /**
     * 是否显示类型
     */
    showType: {
      type: Boolean,
      default: true,
    },
    /**
     * 是否显示简介
     */
    showDescription: {
      type: Boolean,
      default: false,
    },
    cacheTime: {
      type: Number,
      default: 60000,
    },
    tableKey: {
      type: Number,
      default: 0,
    },
    previewSourceUrl: {
      type: String,
      default: "/group/file/download",
    },
  },
  data() {
    return {
      //查询
      query: {
        page: 1,
        pageSize: 10,
        name: "",
        unitId: null,
      },
      id: null,
      //文件上传的时候的文件夹id
      uploadId:null,
      //文件上传的时候的企业id
      uploadUnitId:this.defaultUnitId,
      total: null,
      tableData: [],
      unitList: [],
      // 修改
      isChangingFile: false,
      editForm: {
        id: null,
        name: "",
        description: "",
        unitId: null,
      },
      // 上传文件
      isUploading: false,
      fileList: [],
      action: "",
      file: "",
      // 浏览文件
      previewMode: false,
      src: null,
      importHeaders: { token: sessionStorage.getItem("token") },
      // 文件下载
      downloadUrl:"/group/file/download"
    };
  },
  computed:{
    labelNameC(){
      return this.labelName + "名称"
    }
  },
  mounted() {
    this.query.unitId = this.defaultUnitId
    this.getUnitNameList();
  },
  methods: {
    //尾矿库列表类型
    async getUnitNameList() {
      const res = await getUnitNameList();
      this.unitList = res.parameter;
      this.getDirectory();
    },
    getDirectory() {
      axios({
        method: "get",
        url:
          "/group/file/directory/" +
          this.uniqueName +
          `?unitId=${this.query.unitId}`,
      }).then((res) => {
        this.id = res.data.parameter.id
        this.uploadId = res.data.parameter.id
        this.action =
          `${BACKEND_ROOT}/group/file/upload?parentId=` +
          this.uploadId
        this.getFileList();
      });
    },
    async getFileList() {
      //如果是请求全部企业的文件的话,请求las
      if (this.query.unitId === 0){
        let res = await axios.get("/group/file/las",{
          params:{
            page:this.query.page,
            pageSize:this.query.pageSize,
            uniqueName:this.uniqueName
          }
        })
        this.tableData = res.data.parameter.files
        this.total = res.data.parameter.count
      }
      //如果是其他企业,请求ls
      else{
        const res = await getFileList({
          id: this.id,
          page: this.query.page,
          pageSize: this.query.pageSize,
        });
        this.tableData = res.parameter;
        let t = await axios({
          method:"get",
          url:"/group/file/count",
          params:{
            id:this.id
          }
        })
        this.total = t.data.parameter
      }
    },
    // 监听 pageSize 改变的事件
    handleSizeChange(val) {
      this.query.pageSize = val;
      this.searchFile();
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(val) {
      this.query.page = val;
      this.searchFile();
    },
    // 当select组件发生变化的时候执行函数
    elSelectChange(val){
      this.uploadUnitId = val
      axios({
        method: "get",
        url:
          "/group/file/directory/" +
          this.uniqueName +
          `?unitId=${val}`,
      }).then((res) => {
        this.id = res.data.parameter.id
        this.uploadId = res.data.parameter.id
        this.action =
          `${BACKEND_ROOT}/group/file/upload?parentId=` +
          this.uploadId
      });
    },
    elUploadSelectChange(val){
      axios({
        method: "get",
        url:
          "/group/file/directory/" +
          this.uniqueName +
          `?unitId=${val}`,
      }).then((res) => {
        this.uploadId = res.data.parameter.id
        this.action =
          `${BACKEND_ROOT}/group/file/upload?parentId=` +
          this.uploadId
      });
    },
    // 查询
    async getSearchFile() {
      this.query.page = 1;
      axios({
        method: "get",
        url:
          "/group/file/directory/" +
          this.uniqueName +
          `?unitId=${this.query.unitId}`,
      }).then((res) => {
        this.id = res.data.parameter.id
        this.searchFile();
      });
    },
    async searchFile() {
      if (this.query.name === "") {
        this.getFileList();
      }
      else {
        if (this.query.unitId === 0){
          let res = await axios.get("/group/file/search/all-files",{
            params:{
              page:this.query.page,
              pageSize:this.query.pageSize,
              uniqueName:this.uniqueName,
              name:this.query.name
            }
          })
          this.tableData = res.data.parameter.files;
          this.total = res.data.parameter.count
        }else{
        let res = await getSearchFile({
          page: this.query.page,
          pageSize: this.query.pageSize,
          name: this.query.name,
          parentId: this.id,
        });
        if (res.resultCode === "200") {
          if (res.parameter.length >= 1) {
            this.$message.success({
              message: "查询成功",
              offset: 400,
              duration: 1000,
            });
            let temp = await axios.get("/group/file/search/meta", {
              params: {
                name: this.query.name,
                parentId: this.id,
              }
            })
            this.tableData = res.parameter;
            this.total = temp.data.parameter.length
          }
          if (res.parameter.length == 0) {
            {
              this.$message({
                message: "暂无数据",
                offset: 400,
                duration: 1000,
              });
              this.tableData = [];
              this.total = 0;
            }
          }
        }
        }
      }
    },
    // 上传文件
    submitUpload() {
      console.log("action=="+this.action)
      this.action =
        `${BACKEND_ROOT}/group/file/upload?parentId=` +
        this.uploadId
      this.$refs.upload.submit();
      this.isUploading = false;
    },
    handleSuccess(){
      this.getFileList();
    },
    handlePreview(file) {
      console.log(file);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    // 浏览文件
    async handleEdit(row) {
      this.src = BACKEND_ROOT + "/group/file/download/" + row.id + "." + row.ext;
      this.$refs.previewer.$emit("reload", row.name, row.ext, this.src, row.id);
      // try{
      //   let tempSrc = BACKEND_ROOT + "/group/file/download/" + row.id + "." + row.ext;
      //   //带token的获取
      //   let token = sessionStorage.getItem('token')
      //   let request = new XMLHttpRequest();
      //   request.responseType = 'blob';
      //   request.open('get',tempSrc,true);
      //   request.setRequestHeader('token',token);
      //   request.onreadystatechange = e =>{
      //     if (request.readyState === XMLHttpRequest.DONE && request.status === 200){
      //       console.log("done")
      //       this.src = URL.createObjectURL(request.response);
      //       console.log(this.src)
      //       this.$refs.previewer.$emit("reload", row.name, row.ext, this.src, row.id);
      //     }
      //   };
      //   request.send(null);
      // }catch(err){
      //   this.previewUnsupported();
      //   throw err;
      // }
    },
    previewUnsupported() {
      this.$alert("无法预览此文件。", "无法预览", { type: "error" });
    },
    previewLoading() {
      this.previewMode = true;
    },
    // 修改文件名
    updateFileInfo(row) {
      console.log(row);
      this.isChangingFile = true;
      this.editForm.id = row.id;
      this.editForm.name = row.name;
      this.editForm.description = row.description;
    },
    // 确定修改
    commitChangeFile() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          const formData = new FormData();
          for (const [key, value] of Object.entries(this.editForm)) {
            formData.append(key, value);
          }
          axios({
            method: "put",
            url: "/group/file/move",
            data: formData,
          }).then((res) => {
            console.log(res);
            if (res.data.resultCode == 200) {
              this.getFileList();
              this.$message({
                type: "success",
                message: "修改成功",
                offset: 400,
                duration: 1000,
              });
            } else if (res.data.resultCode == "400") {
              this.$message({
                type: "error",
                message: "修改失败",
                offset: 400,
                duration: 1000,
              });
            }
            this.isChangingFile = false;
          });
        } else {
          this.$message({
            type: "error",
            message: "请完成表单",
            offset: 400,
            duration: 1000,
          });
        }
      });
    },
    // 删除文件
    delFile(id) {
      this.$confirm("确定删除吗？")
        .then((_) => {
          axios({
            method: "DELETE",
            url: "/group/file/remove/" + `${id}`,
          }).then((res) => {
            if (res.data.resultCode === "200") {
              this.getFileList();
              this.$message({
                type: "success",
                message: "删除成功",
                offset: 400,
                duration: 1000,
              });
            } else {
              this.$message({
                type: "error",
                message: res.data.message,
                offset: 400,
                duration: 1000,
              });
            }
          }).catch(err=>{
            this.$message({
              type: "error",
              message: err.message,
              offset: 400,
              duration: 1000,
            });
          });
        })
        .catch((_) => {
          this.$message({
            type: "info",
            message: "已取消删除",
            offset: 400,
            duration: 1000,
          });
        });
    },
    //下载文件
    async delStation(row) {
      window.open(`${this.$http.defaults.baseURL}${this.downloadUrl}/${row.id}.${row.ext}`)
      console.log(row);
      // let token = sessionStorage.getItem('token')
      // let url = `${this.$http.defaults.baseURL}${this.downloadUrl}/${row.id}.${row.ext}`
      // let xhr = new XMLHttpRequest();
      // xhr.open('get', url, true);
      // xhr.responseType = "blob";
      // xhr.setRequestHeader('token',token);
      // xhr.onreadystatechange = e =>{
      //   if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200){
      //     let downLoadSrc = URL.createObjectURL(xhr.response);
      //     let link = document.createElement("a");
      //     link.style.display = "none";
      //     link.href = downLoadSrc;
      //     link.download = `${row.name}.${row.ext}`
      //     document.body.appendChild(link);
      //     link.click();
      //   }
      // };
      // xhr.send(null);
    },
  },
};
</script>
<style scoped>
.content {
  /* padding: 20px; */
  font-size: 0.01rem;
  height: 80vh;
}
.el-table-box {
  margin-bottom: 0.1rem;
  display: block;
  height: 68vh;
  overflow: auto;
}
.el-table::before {
  z-index: inherit;
}
table {
  text-align: center;
}
.upload-demo {
  padding-left: 110px;
}
.select-enterprise{
  width: 40rem;
  display: inline-block;
}
</style>
